package com.csg.ses.vo.common;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import lombok.Data;

/**
 * API返回结果
 * @auther wangjun
 * @date 2020/11/16
 */
@Data
@ApiModel(description = "API返回结果")
public class Result<T> {
    protected int code;
    protected String msg;
    protected T data;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected PageInfo page;

    private Result() {
        this(ResultStatus.SUCCESS);
    }

    /**
     * 返回结果封装（分页/不分页）
     * @param data
     * @param resultStatus
     */
    public Result(T data, ResultStatus resultStatus) {
        this(resultStatus);
        if (data != null && data.getClass().equals(Page.class)) {   //分页
            PageInfo pageInfo = new PageInfo();
            pageInfo.setCurrent(((Page<T>) data).getCurrent());
            pageInfo.setSize(((Page<T>) data).getSize());
            pageInfo.setTotal(((Page<T>) data).getTotal());
            pageInfo.setPages(((Page<T>) data).getPages());
            this.data = (T) ((Page<T>) data).getRecords();
            this.page = pageInfo;
        } else {
            this.data = data;
        }
    }

    public Result(ResultStatus resultStatus) {
        this.code = resultStatus.getCode();
        this.msg = resultStatus.getMessage();
    }

    public Result(T data) {
        this();
        this.data = data;
    }

    public static Result success() {
        return new Result();
    }

    public static Result fail(ResultStatus resultStatus){
        return new Result(resultStatus);
    }

    public static Result fallBack() {
        return new Result(ResultStatus.FALLBACK);
    }

    @Override
    public String toString(){
        return JSONUtil.toJsonStr(this);
    }
}